package cn.dida.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import cn.dida.model.Branch;
import cn.dida.model.Pageable;
import cn.dida.model.Prize;
import cn.dida.model.PrizeBranch;

/**
 * <p>奖品管理  数据交互类</p>
 * @author lisha
 * @date 2016-11-10 14:59
 * */
@Repository
public class PrizeDao extends DaoBase {
	/**
	 * 根据奖品id获取已关联的网点
	 * @param prizeId 奖品id
	 * @return List<PrizeBranch> 奖品列表集合
	 * @date 2016-11-20 10:20
	 * */
	public List<Branch> getBranchListByPrizeId(String prizeId) {
        String sql = "select * from branch where id in(select branch_id from prize_branch where prize_id=?)";//查询正常可用的奖品
        List<Branch> result = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(Branch.class),prizeId);
        return result;
    }
	/**
	 * 奖品列表,活动中使用
	 * @return List<Prize> 奖品列表集合
	 * @date 2016-11-18 10:20
	 * */
	public List<Prize> query(Integer compayId) {
        String sql = "select * from prize where sta = 1 and company_id = ?";//查询正常可用的奖品
        List<Prize> result = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(Prize.class),compayId);
        return result;
    }
	/**
	 * 增加奖品记录
	 * @param prize 奖品实体类
	 * @return int 受影响的记录行数
	 * @date 2016-11-10 15:20
	 * */
	public int insert(Prize prize){
		String str = prize.getSelectedBranch();
		 String sql = "insert into prize(name, type, price, stock,shipping_method, image, summary,"
		 		+ " c_time, c_admin, u_time, "
		 		+ "u_admin,sta,company_id) values (:name, :type, :price, :stock, :shippingMethod, :image, :summary, :cTime, "
		 		+ ":cAdmin, :uTime, :uAdmin, :sta,:companyId)";
	       /* HashMap<String, Object> paramMap = new HashMap<>();
	        paramMap.put("name", prize.getName());
	        paramMap.put("type", prize.getType());
	        paramMap.put("price", prize.getPrice());
	        paramMap.put("stock", prize.getStock());
	        paramMap.put("shippingMethod", prize.getShippingMethod());//配送方式
	        paramMap.put("image", prize.getImage());
	        paramMap.put("summary", prize.getSummary());
	        paramMap.put("cTime", DateUtils.STYLE3.format(new Date()));
	        paramMap.put("cAdmin", prize.getcAdmin());
	        paramMap.put("uTime", DateUtils.STYLE3.format(new Date()));
	        paramMap.put("uAdmin", prize.getuAdmin());
	        paramMap.put("sta", 1);//默认正常可用状态
	        namedParameterJdbcTemplate.update(sql, paramMap);*/
		 	long current = new Date().getTime();
		 	prize.setcTime(current);
		 	prize.setuTime(current);
		 	prize.setSta(1);//默认正常可用状态
	        
	        KeyHolder keyHolder=new GeneratedKeyHolder(); 
	        //增加活动基本信息
	        SqlParameterSource ps=new BeanPropertySqlParameterSource(prize); 
	        namedParameterJdbcTemplate.update(sql, ps, keyHolder);
	        
	        int prizeId = keyHolder.getKey().intValue();
	        //增加奖品与网点关联关系
	        PrizeBranch pb = new PrizeBranch();
	        if(StringUtils.isNotBlank(str)){
	        	String[] pros = str.split(",");
	        	for(int i = 0; i < pros.length; i++){
		        	pb.setBranchId(Integer.parseInt(pros[i]));
		        	pb.setPrizeId(prizeId);
		        	this.insertPrizeBranch(pb);
		        }
	        }
	        
	        
	        return 1;
	}
	/**
	 * 增加奖品与网点关联关系
	 * @param pb 奖品与网点关联 实体类
	 * @date 2016-11-20 14:01
	 * */
	private void insertPrizeBranch(PrizeBranch pb){
		String sql = "insert into prize_branch(prize_id, branch_id"
		 		+ " ) values (:prizeId, :branchId)";
	        HashMap<String, Object> paramMap = new HashMap<>();
	        paramMap.put("prizeId", pb.getPrizeId());
	        paramMap.put("branchId", pb.getBranchId());
	        
	        namedParameterJdbcTemplate.update(sql, paramMap);
	}
	
	/**
	 * 修改奖品信息
	 * @param prize 奖品实体类
	 * @return int 受影响的记录行数
	 * @date 2016-11-10 15:33
	 * */
	public int update(Integer companyId,Prize prize) {
        String sql = "update prize set name=:name, type=:type, price=:price, stock=:stock, "
        		+ "shipping_method=:shippingMethod, image=:image, summary=:summary, u_admin=:uAdmin,"
        		+ "u_time=:uTime where id=:id and company_id=:companyId";
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", prize.getName());
        paramMap.put("type", prize.getType());
        paramMap.put("price", prize.getPrice().doubleValue());
        paramMap.put("stock", prize.getStock());
        paramMap.put("shippingMethod", prize.getShippingMethod());
        paramMap.put("image", prize.getImage());
        paramMap.put("summary", prize.getSummary());
        paramMap.put("uAdmin", prize.getuAdmin());
        paramMap.put("uTime", new Date().getTime());
        paramMap.put("id", prize.getId());
        paramMap.put("companyId", companyId);
        
      //增加奖品与网点关联关系
        String str = prize.getSelectedBranch();
        PrizeBranch pb = new PrizeBranch();
        if(StringUtils.isNotBlank(str)){
        	String[] pros = str.split(",");
        	for(int i = 0; i < pros.length; i++){
	        	pb.setBranchId(Integer.parseInt(pros[i]));
	        	pb.setPrizeId(prize.getId());
	        	this.insertPrizeBranch(pb);
	        }
        }
        //删除已存在的自提网点
        if(StringUtils.isNotBlank(prize.getDelSelectedBranch())){
        	String[] delBranchIds = prize.getDelSelectedBranch().split(",");
        	if(delBranchIds.length > 0){
        		for(int i = 0;i < delBranchIds.length; i++){
            		this.deleteBranchById(Integer.valueOf(delBranchIds[i]));
            	}
        	}
        }
        
        return namedParameterJdbcTemplate.update(sql, paramMap);
    }
	/**
	 * 删除奖品
	 * @param id 奖品记录行号
	 * @return int 受影响的记录数
	 * @date 2016-11-10 15:36
	 * */
	public int delete(Integer companyId,int id) {
        String sql = "delete from prize where id = ? and company_id=?";
        return jdbcTemplate.update(sql, id,companyId);
    }
	/**
	 * 根据id获取奖品详情
	 * @param id 奖品记录行号
	 * @return prize 奖品详情
	 * @date 2016-11-10 15:39
	 * */
	public Prize getPrizeById(Integer id, Integer companyId) {
        String sql = "select * from prize where id = ? and company_id = ?";
        List<Prize> result = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Prize.class),id,companyId);
        if(result.size() > 0){
        	return result.get(0);
        }else{
        	return new Prize();
        }
    }
	
	/**
	 * 奖品列表
	 * @param name 奖品名称
	 * @param type 奖品类型（1红包，2实物，3优惠券）
	 * @param page 分页游标
	 * @return Pageable<Prize> 奖品分页列表
	 * @date 2016-11-10 15:52
	 * */
	public Pageable<Prize> query(Integer companyId,String name, int type,int page) {
        Object[] args = {};
        StringBuffer sqlQueryResultCount = new StringBuffer("select count(1) from prize where 1 = 1 and company_id=? ");
        StringBuffer sqlQueryResult = new StringBuffer("select * from prize where 1 = 1 and company_id=? ");

        args = ArrayUtils.add(args, companyId);
        StringBuffer sqlWhere = new StringBuffer() ;
        if(StringUtils.isNotBlank(name)){
        	sqlWhere.append("and name like ?");
        	args = ArrayUtils.add(args, "%" + name + "%");
        }
        if(type != 0){
        	sqlWhere.append(" and type = ?");
        	args = ArrayUtils.add(args, type);
        }

        Integer resultTotal = 0;
        // 查询记录总数
        if(sqlWhere != null){
        	resultTotal = jdbcTemplate.queryForObject(sqlQueryResultCount.append(sqlWhere).toString(), Integer.class, args);
        	// 查询记录
        	sqlQueryResult.append(sqlWhere).append("  order by c_time desc limit ?,?");
        }else{
        	resultTotal = jdbcTemplate.queryForObject(sqlQueryResultCount.toString(), Integer.class, args);
        	sqlQueryResult.append("  order by c_time desc limit ?,?");
        }
        
        args = ArrayUtils.add(args, (page - 1) * getPageSize());
        args = ArrayUtils.add(args, getPageSize());
        List<Prize> result = jdbcTemplate.query(sqlQueryResult.toString(), args, new BeanPropertyRowMapper<>(Prize.class));
        /*if(result.size() > 0){
        	int flag = 0;
        	for(int i = 0; i < result.size(); i++){
        		flag = this.getActivityPrizeByPrizeId(result.get(i).getId());
        		result.get(i).setDelFlag(flag);
        	}
        }*/
        return new Pageable<>(page, getPageSize(), resultTotal, result);
    }
	/**
	 * 根据奖品id 获取中奖规则
	 * @param prizeId 奖品id
	 * @return int 该奖品是否已参加了活动，0未参加活动，1已参加活动
	 * @date 2016-11-26 11:43
	 * */
	/*private int getActivityPrizeByPrizeId(Integer prizeId){
		String sql = "select * from activity_prize where prize_id = ? ";
		List<ActivityPrize> result = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ActivityPrize.class),prizeId);
		if(result.size() > 0){
			return 1;
		}else{
			return 0;
		}
	}*/
	
	/**
	 * 删除奖品与自提网点关联
	 * @param branchId 奖品记录行号
	 * @return int 受影响的记录数
	 * @date 2016-11-26 11:43
	 * */
	public int deleteBranchById(int branchId) {
        String sql = "delete from prize_branch where branch_id = ?";
        return jdbcTemplate.update(sql, branchId);
    }
	/**
	 * 根据奖品id获取奖品与自提网点关联信息
	 * @param prizeId 奖品id
	 * @return List<PrizeBranch> 奖品与自提网点关联列表
	 */
	public List<PrizeBranch> getPrizeBranchListByPrizeId(Integer prizeId){
		String sql = "select * from  prize_branch where prize_id = ?";
		List<PrizeBranch> result = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PrizeBranch.class),prizeId);
    	return result;
	}
	
	/**
     * 根据奖品名称 查看奖品是否存在
     * @param companyId 公司名称
     * @param name 奖品名称
     * @return boolean true存在，false不存在
     * @date 2016-12-12 11:21
     * */
    public boolean isExistsPrize(Integer companyId, String name){
    	String sql = "SELECT * from prize WHERE company_id = ? and `name` = ? ";
    	List<Prize> result = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Prize.class),companyId,name);
    	if(result.size() > 0){
    		return true;
    	}else{
    		return false;
    	}
    }
}
